package com.sunday.common.mq.kafka.study.spring.e18_Dead_Letter;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.DltHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.RetryableTopic;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.retrytopic.SameIntervalTopicReuseStrategy;
import org.springframework.kafka.support.SendResult;
import org.springframework.retry.annotation.Backoff;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi {

    private final Random rand = new Random();

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) throws InterruptedException, ExecutionException {

        CompletableFuture<SendResult<Object, Object>> future;
        ValidatedClass validatedClass = new ValidatedClass(rand.nextInt(2));
        log.info("send : {}", validatedClass);
        future = kafkaTemplate.send(topic, key, validatedClass.toString());
        log.info("{}", future.get());
    }

    @KafkaListener(
            id = "myId_11",
            topics = "topic11",
            clientIdPrefix = "TEST11"
    )
    /**
     * 极致空间换时间
     * https://blog.csdn.net/qq_35270227/article/details/130008855
     */
    @RetryableTopic(
            attempts = "4",
            backoff = @Backoff(delay = 5000, multiplier = 2),
            sameIntervalTopicReuseStrategy = SameIntervalTopicReuseStrategy.SINGLE_TOPIC
    )
    public void listen11(ConsumerRecord<String, String> record) {
        log.info("[收到测试消息] message = {}", record.value());
        throw new RuntimeException("error");
    }

    @DltHandler
    public void dltHandler(ConsumerRecord<String, String> record) {
        log.info("[进入死信队列] message = {}", record.value());
    }

}
